import React from 'react';
import {Table, Spin, Row, Col, Popconfirm, Affix, Alert, message as componentMessage} from 'antd';
import PropTypes from 'prop-types';
import {partStatus, partChannel} from '../Enum';
import routes from './routes';
import {PAGINATION_OPTIONS, TABLE, PAGE_TEN, ROWSELECTION_FIXED_COLUMN_WIDTH, FIXED_COLUMN_WIDTH} from '../constants';
import {conventEnumValueToString} from '../utils';
import style from './style.css';
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import * as actions from './actions';
import {injectIntl} from './intl';
import {freezeApplyReports, thawApplyReports} from './api';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import {Link} from 'react-router-dom';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            isSubmitting: false,
            visible: false,
            currentRecord: {},
            selectedRowKeys: [],
            selectedThawRowKeys: []
        };
        this.handleTableOnChange = this.handleTableOnChange.bind(this);
    }
    affixOnChange = () => this.forceUpdate();
    handleDetail= e => {
        this.props.history.push(routes.detail.format(e.target.dataset.recordId));
    }
    thawConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        const data = {
            id,
            rowVersion: record.rowVersion
        };
        thawApplyReports([data]).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onConditionsChange();
        });
    }
    freezeConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        const data = {
            id,
            rowVersion: record.rowVersion
        };
        freezeApplyReports([data]).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onConditionsChange();
        });
    }
    handleTableOnChange(pagination, filters, sorter) {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onConditionsChange({
                sortBy: sorter.field,
                sortOrder: sorter.order,
            });
    }
    onClickBatchReceive = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的选项'
            }));
        else {
            this.setState({loading: true});
            const submitData = this.props.data.filter(item => selectIds.includes(item.id)).map(item => ({
                id: item.id,
                rowVersion: item.rowVersion
            }));
            freezeApplyReports(submitData).then(res => {
                this.setState({loading: false});
                if(res.ok) {
                    this.props.onPageSizeChange();
                    this.onEndBatchOperation();
                }
            });
        }
    }
    onClickBatchThaw = () => {
        const selectIds = this.state.selectedThawRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的选项'
            }));
        else {
            this.setState({loading: true});
            const submitData = this.props.data.filter(item => selectIds.includes(item.id)).map(item => ({
                id: item.id,
                rowVersion: item.rowVersion
            }));
            thawApplyReports(submitData).then(res => {
                this.setState({loading: false});
                if(res.ok) {
                    this.props.onPageSizeChange();
                    this.onEndBatchThawOperation();
                }
            });
        }
    }
    onEndBatchOperation = () => {
        this.setState({selectedRowKeys: []});
        this.props.onEndBatchOperation();
    }
    onEndBatchThawOperation = () => {
        this.setState({selectedThawRowKeys: []});
        this.props.onEndBatchThawOperation();
    }

    onSelectedChange = keys => this.setState({
        selectedRowKeys: keys,
        selectedThawRowKeys: keys
    });
    
    render() {
        const {formatMessage, formatNumber} = this.props.intl;
        const isBatchOperatting = this.props.isShowBatchReceivePanel;
        const isShowThaw = this.props.isShowBatchThawPanel;
        const isFreeze = isBatchOperatting ? PERMISSION.freeze : PERMISSION.thaw;
        const Yes = formatMessage({
            id: 'tablePanel.yes',
            defaultMessage: '是'
        });
        const No = formatMessage({
            id: 'tablePanel.no',
            defaultMessage: '否'
        });
        const receiveMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <Popconfirm
                    id="batchReceive"
                    key="batchReceive"
                    getPopupContainer={this.getPopupContainer} title={formatMessage({
                        id: 'tablePanel.Validation.isContinue',
                        defaultMessage: '是否继续?'
                    })} okText={formatMessage({
                        id: 'tablePanel.btn.Confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={formatMessage({
                        id: 'tablePanel.btn.Cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onClickBatchReceive}>
                    <a className={style.panelalertMessage} >{formatMessage({
                        id: 'tablePanel.btn.BatchReceive',
                        defaultMessage: '批量冻结'
                    })}</a>
                </Popconfirm>
            </Col>
        </Row>);
        const thawMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <Popconfirm
                    id="batchThaw"
                    key="batchThaw"
                    getPopupContainer={this.getPopupContainer} title={formatMessage({
                        id: 'tablePanel.Validation.isContinue',
                        defaultMessage: '是否继续?'
                    })} okText={formatMessage({
                        id: 'tablePanel.btn.Confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={formatMessage({
                        id: 'tablePanel.btn.Cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onClickBatchThaw}>
                    <a className={style.panelalertMessage} >{formatMessage({
                        id: 'tablePanel.btn.BatchThaw',
                        defaultMessage: '批量解冻'
                    })}</a>
                </Popconfirm>
            </Col>
        </Row>);
        const columns = [
            {
                title: formatMessage({
                    id: 'tablePanel.code',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'code',
                sorter: true,
                render: (text, record) => <a data-record-id={record.id} onClick={this.handleDetail}>{text}</a>
            }, {
                title: formatMessage({
                    id: 'tablePanel.name',
                    defaultMessage: '备件名称'
                }),
                sorter: true,
                dataIndex: 'name',
                render: text => <Ellipsis tooltip fullWidthRecognition length={32}>{text}</Ellipsis>
            }, {
                title: formatMessage({
                    id: 'tablePanel.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(partStatus, text),
            }, {
                title: formatMessage({
                    id: 'tablePanel.partReplacementCode',
                    defaultMessage: '替代件编号'
                }),
                dataIndex: 'partReplacementCode'
            }, {
                title: formatMessage({
                    id: 'tablePanel.alternativePlan',
                    defaultMessage: '替代方案'
                }),
                dataIndex: 'alternativePlan',
            }, {
                title: formatMessage({
                    id: 'tablePanel.isConsume',
                    defaultMessage: '消耗库存'
                }),
                dataIndex: 'isConsume',
            }, {
                title: formatMessage({
                    id: 'tablePanel.airMagneticCheck',
                    defaultMessage: '空运磁检'
                }),
                dataIndex: 'airMagneticCheck',
                render: text => text === true ? Yes : No,
            }, {
                title: formatMessage({
                    id: 'tablePanel.dangerousGoods',
                    defaultMessage: '空运危险'
                }),
                dataIndex: 'dangerousGoods',
                render: text => text === true ? Yes : No,
            }, {
                title: formatMessage({
                    id: 'tablePanel.chemicalCheck',
                    defaultMessage: '化工鉴定'
                }),
                dataIndex: 'chemicalCheck',
                render: text => text === true ? Yes : No,
            }, {
                title: formatMessage({
                    id: 'tablePanel.length',
                    defaultMessage: '长'
                }),
                dataIndex: 'length',
                render: text => formatNumber(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.width',
                    defaultMessage: '宽'
                }),
                dataIndex: 'width',
                render: text => formatNumber(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.height',
                    defaultMessage: '高'
                }),
                dataIndex: 'height',
                render: text => formatNumber(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.grossWeight',
                    defaultMessage: '毛重'
                }),
                dataIndex: 'grossWeight',
                render: text => formatNumber(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.netWeight',
                    defaultMessage: '净重'
                }),
                dataIndex: 'netWeight',
                render: text => formatNumber(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.usagePerCar',
                    defaultMessage: '每车用量'
                }),
                dataIndex: 'usagePerCar',
                render: text => formatNumber(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.minPackSize',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minPackSize',
                render: text => formatNumber(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.description',
                    defaultMessage: '英文描述'
                }),
                dataIndex: 'description'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.operate',
                    defaultMessage: '操作'
                }),
                dataIndex: 'operate',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [];
                    menus.push({
                        id: PERMISSION.freeze,
                        children: (
                            <WrappedPopconfirm
                                id={r.id}
                                key="freeze"
                                title={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                okText={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.confirm',
                                    defaultMessage: '确认'
                                })}
                                cancelText={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.cancel',
                                    defaultMessage: '取消'
                                })}
                                onConfirm={this.freezeConfirm}>
                                <a>{
                                    formatMessage({
                                        id: 'detail.popconfirm.freeze',
                                        defaultMessage: '冻结'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.freeze) && hasPermissions(r.options, PERMISSION.freeze))
                    }, {
                        id: PERMISSION.thaw,
                        children: (
                            <WrappedPopconfirm
                                id={r.id}
                                key="thaw"
                                title={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                okText={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.confirm',
                                    defaultMessage: '确认'
                                })}
                                cancelText={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.cancel',
                                    defaultMessage: '取消'
                                })}
                                onConfirm={this.thawConfirm}>
                                <a>{
                                    formatMessage({
                                        id: 'detail.popconfirm.thaw',
                                        defaultMessage: '解冻'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.thaw) && hasPermissions(r.options, PERMISSION.thaw))
                    }, {
                        id: PERMISSION.update,
                        children: <Link key="update" to={routes.update.format(r.id)}>{formatMessage({
                            id: 'tablePanel.btn.edit',
                            defaultMessage: '编辑'
                        })}</Link>,
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                    });
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        if(!this.props.isDealerUser) {
            columns.splice(17, 0, ...[
                {
                    title: formatMessage({
                        id: 'tablePanel.categoryCode',
                        defaultMessage: '维护车型'
                    }),
                    dataIndex: 'categoryCode',
                }
            ]);
            columns.splice(18, 0, ...[
                {
                    title: formatMessage({
                        id: 'tablePanel.isEOL',
                        defaultMessage: '是否停产'
                    }),
                    dataIndex: 'isEOL',
                    sorter: true,
                    render: text => text === true ? '是' : '否',
                }
            ]);
            columns.splice(19, 0, ...[
                {
                    title: formatMessage({
                        id: 'tablePanel.channel',
                        defaultMessage: '渠道'
                    }),
                    dataIndex: 'channel',
                    sorter: true,
                    render: text => conventEnumValueToString(partChannel, text)
                }
            ]);
        }

        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        
        const rowSelection = (isBatchOperatting || isShowThaw) ? {
            fixed: true,
            type: 'checkbox',
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            getCheckboxProps: record => ({
                disabled: !hasPermissions(record.options, isFreeze)
            }),
            selectedRowKeys: this.state.selectedRowKeys,
            selectedThawRowKeys: this.state.selectedThawRowKeys,
            onChange: this.onSelectedChange
        } : undefined;
        return (
            <Spin spinning={this.props.loading || this.state.isSubmitting} className={style.spin}>
                {isBatchOperatting && <Affix offsetTop={0} className={style.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={receiveMessage} type="warning" closable showIcon
                        closeText={<span className={style.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndBatchOperation} />
                </Affix>}
                {isShowThaw && <Affix offsetTop={0} className={style.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={thawMessage} type="warning" closable showIcon
                        closeText={<span className={style.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndBatchThawOperation} />
                </Affix>}
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowSelection={rowSelection}
                    onChange={this.handleTableOnChange}
                    rowKey="id"
                    pagination={pagination}
                    {...TABLE} />
            </Spin>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    total: PropTypes.number.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onEndBatchOperation: PropTypes.func.isRequired,
    onEndBatchThawOperation: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDealerUser = selectorFactory(['page', 'domainData', 'initData', 'isDealerUser']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'pageTableCondition', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'pageTableCondition', 'pageSize']),
    isShowBatchReceivePanel: state.getIn(['page', 'ui', 'showBatchReceivePanel']),
    isShowBatchThawPanel: state.getIn(['page', 'ui', 'showBatchThawPanel']),
    permissions: getPermissions(state),
    isDealerUser: getDealerUser(state)
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) => dispatch(actions.changePageForList({
        pageSize,
        pageIndex: PAGE_TEN.index
    })),
    onPageIndexChange: pageIndex => dispatch(actions.changePageForList({
        pageIndex: pageIndex - 1
    })),
    onConditionsChange: obj => dispatch(actions.searchList(obj)),
    onEndBatchOperation: () => dispatch(actions.clearBatchData()),
    onEndBatchThawOperation: () => dispatch(actions.clearBatchThawData()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
